/*
 * myvector.cpp
 *
 *  Created on: Nov 18, 2016
 *      Author: swolice
 */

#include "myvector.h"

template <class T>
myvector<T>::myvector()
{
	p=nullptr;
	n=realn=0;
}

template <class T>
myvector<T>::~myvector()
{
	if (p!=nullptr) {
		delete []p;
		p=nullptr;
	}
}

template <class T>
void myvector<T>::push_bach(T t)
{
	if (p==nullptr) {
		p=new T;
		*p=t;
		realn=n=1;
	} else {
		T *ptemp=new T[n+1];
		for (int i = 0; i < n; ++i) {
			*(ptemp+i)=*(p+i);
		}
		*(ptemp+n)=t;
		delete []p;
		p=ptemp;
		realn+=1;
		n+=1;
	}
}

template <class T>
void myvector<T>::show()
{
	if (p==NULL) {
		return;
	} else {
		for (int i = 0; i < realn; ++i) {
			std::cout<<p[i]<< " ";
		}
		std::cout<<std::endl;
	}
}

template <class T>
T * myvector<T>::find(T t)
{
	for (int i = 0; i < realn; ++i) {
		if (t==*(p+i)) {
			return p+i;
		}
	}
	return nullptr;
}

template <class T>
void myvector<T>::change(T *pos, T t)
{
	if (pos==nullptr) {
		return;
	} else {
		*pos=t;
	}
}

template <class T>
void myvector<T>::del(T t)
{
	int pos=-1;
	for (int i = 0; i < realn; ++i) {
		if (t==*(p+i)) {
			pos=i;
			break;
		}
	}
	if (pos!=-1) {
		if (pos=realn-1) {
			realn-=1;
		} else {
			for (int i = 0; i < realn-1; ++i) {
				p[i]=p[i+1];
			}
			realn-=1;
		}
	}
}


template <class T>
void myvector<T>::insert(T findt, T t)
{
	if (n==realn) {
		{
			int pos=-1;
			for (int i = 0; i < realn; ++i) {
				if (findt==*(p+i)) {
					pos=i;
					break;
				}
			}
			if (pos!=-1) {
				{
					T *ptemp=new T[n+1];
					for (int i = 0; i < n; ++i) {
						*(ptemp+i)=*(p+i);
					}
					delete[] p;
					p=ptemp;
					realn+=1;
					n+=1;
				}
				for (int i = realn-2; i >=pos; ++i) {
					p[i+1]=p[i];
				}
				p[pos]=t;
			}
		}
	} else {
		int pos=-1;
		for (int i = 0; i < realn; ++i) {
			if (findt==*(p+i)) {
				pos=i;
				break;
			}
		}
		if (pos!=-1) {
			for (int i = realn-1; i>=pos; ++i) {
				p[i+1]=p[i];
			}
			p[pos]=t;
			realn+=1;
		}
	}
}

template <class T>
T myvector<T>::operator [](int i)
{
	if (i<0||i>=realn) {
		return NULL;
	}

	return p[i];
}



